#include <crt_util.h>

#define LOG_FORMAT    "[%s][%s][%s][%d]==>"
#define LOG_PAGE_SIZE 1024

#ifdef __ANDROID__

#include <android/log.h>
/*
 * Send a simple string to the log.
 * int __android_log_write(int prio, const char* tag, const char* text);
 */
#endif

static int _log_print(int proi, const char* tag, int line, const char* func, const char* fmt, va_list ap)
{
    char* msg = NULL;
    int hmsglen = 0;
    int msglen = 0;

    char tm[81] = {0x00};
    int rc;
    rc = get_time_t(tm, 80);
    rc_error(rc != S_ERROR, E_FAIL);

    msg = (char*)heap_calloc(LOG_PAGE_SIZE, sizeof(char));
    rc_error(msg != NULL, S_ERROR);

#if (TARGET_OS == OS_WIN)
    hmsglen = sprintf_s(msg, LOG_PAGE_SIZE, LOG_FORMAT, tag, tm, func, line);
#else
    hmsglen = snprintf(msg, LOG_PAGE_SIZE, LOG_FORMAT, tag, tm, func, line);
#endif

    if (hmsglen > 0 && hmsglen < LOG_PAGE_SIZE) {
        msglen = LOG_PAGE_SIZE - hmsglen;
    } else {
        msglen = LOG_PAGE_SIZE;
        hmsglen = 0;
    }
#if (TARGET_OS == OS_WIN)
    vsnprintf_s(msg + hmsglen, msglen, msglen, fmt, ap);
#else
    vsnprintf(msg + hmsglen, msglen, fmt, ap);
#endif

#ifdef __ANDROID__
    __android_log_write(proi, "", msg);
#else
    debug_view(msg);
    debug_view("\n");
#endif

    heap_free(msg);
    return S_SUCCESS;
}

int log_print(int proi, const char* tag, int line, const char* func, const char* fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);

    _log_print(proi, tag, line, func, fmt, ap);

    va_end(ap);
    return S_SUCCESS;
}
